﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpRomans.Support
{
	internal static class EnumerableExtensions
	{
		internal static string ToDelimitedString<T>(this IEnumerable<T> source)
		{
			return toDelimitedString(source, ", ", t => t.ToString());
		}

		internal static string ToDelimitedString<T>(this IEnumerable<T> source, Func<T, string> toString)
		{
			return toDelimitedString(source, ", ", toString);
		}

		private static string toDelimitedString<T>(IEnumerable<T> source, string delimiter, Func<T, string> toString)
		{
			if (source == null) return null;

			StringBuilder sb = new StringBuilder();
			foreach (var item in source)
			{
				sb.Append(toString(item));
				sb.Append(delimiter);
			}
			if (sb.Length >= delimiter.Length)
			{
				sb.Remove(sb.Length - delimiter.Length, delimiter.Length);
			}
			return sb.ToString();
		}
	}
}
